package com.jenkins.test.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.io.Serializable;

/**
 * @version V1.0.0
 * @ClassName: {@link RedisConfig}
 * @Description: redis 配置
 * @author: Lanzhou
 * @date: 2020/12/7 14:26
 * @Copyright:2020 All rights reserved.
 */
@Configuration
public class RedisConfig {

    /**
     * 缓存对象必须实现序列化
     *
     * @param connectionFactory 链接工厂
     * @return
     */
    @Bean
    public RedisTemplate<String, Serializable> redisTemplate(LettuceConnectionFactory connectionFactory) {
        RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
        initRedisTemplate(connectionFactory, redisTemplate);
        return redisTemplate;
    }

    /**
     * 缓存对象必须实现序列化
     *
     * @param connectionFactory 链接工厂
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> objRedisTemplate(LettuceConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        initRedisTemplate(connectionFactory, redisTemplate);
        return redisTemplate;
    }

    /**
     * 初始化 RedisTemplate
     *
     * @param connectionFactory 连接工厂
     * @param redisTemplate     redis模板
     */
    private void initRedisTemplate(LettuceConnectionFactory connectionFactory, RedisTemplate<String, ?> redisTemplate) {
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        ObjectMapper om = new ObjectMapper();
        // 将日期直接转化为时间戳, 防止LocalDateTime.class 反序列化出错
        om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        om.registerModule(new JavaTimeModule());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer(om));
        redisTemplate.setHashValueSerializer(new StringRedisSerializer());
        redisTemplate.setConnectionFactory(connectionFactory);
    }


}
